package Q209;

/**
 * 长度最小的子数组
 *
 * @author 23737
 * @time 2021.12.02
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(new Solution().minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3}));
    }
}

/**
 * 暴力
 */
class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int sum = 0;
        int res = Integer.MAX_VALUE;
        int len = 0;
        for (int i = 0; i < nums.length; i++) {
            sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                if (sum >= target) {
                    len = j - i + 1;
                    res = res > len ? len : res;
                    break;   //只跳出了第二层循环
                }
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }

    /**
     * 滑动窗口
     * @param target
     * @param nums
     * @return
     */
    public int minSubArrayLen2(int target, int[] nums) {
        int res = Integer.MAX_VALUE;
        int left = 0;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            //这里要用while
            while (sum >= target){
                res = Math.min(res,i-left+1);
                sum -= nums[left++];
            }
        }
        return res == Integer.MAX_VALUE ? 0:res;
    }
}
